package com.woniu.elderly.wares.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.entity.Result;
import com.woniu.common.entity.WaresImg;
import com.woniu.elderly.wares.mapper.WaresImgMapper;
import com.woniu.elderly.wares.service.WaresImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
* @author Administrator
* @description 针对表【wares_img】的数据库操作Service实现
* @createDate 2024-08-02 11:57:49
*/
@Service
public class WaresImgServiceImpl extends ServiceImpl<WaresImgMapper, WaresImg>
    implements WaresImgService {

    @Autowired
    private WaresImgMapper waresImgMapper;
    @Override
    public String addpicture(MultipartFile file) {
        // 获取文件后缀
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        String endpoint ="https://oss-cn-beijing.aliyuncs.com";
        String id = "LTAI5t6HiybXVxKxytUcEA9d";
        String key = "nAE8IfEVDMCoUsUnbY1dJEyxBAxd4x";
            // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, id, key);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ok86";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "2024/"+ UUID.randomUUID().toString().replace("-", "")+substring;

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }  catch (Exception ce) {
            throw new RuntimeException(ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url = "https://ok86.oss-cn-beijing.aliyuncs.com/"+objectName;
        //存入数据库
        WaresImg waresImg = new WaresImg();
        waresImg.setPath(url);
        waresImgMapper.insert(waresImg);

        return  url;
    }
}




